﻿using Castle.DynamicProxy;

namespace CastleInterceptorDemo.Api
{
    public class LogAsyncInterceptor : IAsyncInterceptor
    {
        private readonly ILogger<LogAsyncInterceptor> _logger;

        public LogAsyncInterceptor(ILogger<LogAsyncInterceptor> logger)
        {
            _logger = logger;
        }

        public void InterceptSynchronous(IInvocation invocation)
        {
            throw new NotImplementedException();
        }

        public void InterceptAsynchronous(IInvocation invocation)
        {
            throw new NotImplementedException();
        }

        public void InterceptAsynchronous<TResult>(IInvocation invocation)
        {
            _logger.LogWarning($"Executing {invocation.Method.Name} with parameters: " + string.Join(", ", invocation.Arguments.Select(a => a?.ToString()).ToArray()));
            invocation.ReturnValue = InternalInterceptAsynchronous<TResult>(invocation);
            _logger.LogWarning($"Finished executing {invocation.Method}");
        }

        private async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
        {
            TResult result;

            invocation.Proceed();
            var task = (Task<TResult>)invocation.ReturnValue;
            result = await task;

            return result;
        }
    }
}
